package com.ksyun.campus.dataserver.services;

import com.google.gson.Gson;
import com.ksyun.campus.dataserver.domain.DSInstanceInfo;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RegistService implements ApplicationRunner {

    @Autowired
    private String ipAddress;

    @Value("${server.port}")
    private Integer port;

    @Value("${az.rack}")
    private String rack;

    @Value("${az.zone}")
    private String zone;


    @Autowired
    private Gson gson;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        registToCenter();
    }

    @Autowired
    private CuratorFramework curatorFramework;

    private Map<String, Long> lastHeartbeatTimeMap = new ConcurrentHashMap<>();

    private String zookeeperPath = "/ds";

    public void registToCenter() {
        try {
            Long totalCapacity = 1024L * 1024L * 1024L;
            Long usableCapacity = 1024L * 1024L * 1024L;

            DSInstanceInfo dsInstanceInfo = new DSInstanceInfo(ipAddress, port, totalCapacity, usableCapacity, rack, zone);
            String instanceJson = gson.toJson(dsInstanceInfo);

            // 为实例创建临时节点
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(zookeeperPath + "/" + ipAddress + ":" + port, instanceJson.getBytes());

            log.info("{} 实例 {} 注册成功。", ipAddress + ":" + port, instanceJson);

            // 使用临时节点，不再需要单独的心跳机制
        } catch (Exception e) {
            log.info("实例注册失败：" + e.getMessage());
        }
    }

    @PreDestroy
    public void unregisterFromCenter() {
        try {
            String nodePath = zookeeperPath + "/" + ipAddress + ":" + port;

            if (curatorFramework.checkExists().forPath(nodePath) != null) {
                curatorFramework.delete().forPath(nodePath);
                log.info("成功删除注册节点：{}", nodePath);
            } else {
                log.info("注册节点不存在：{}", nodePath);
            }
        } catch (Exception e) {
            log.info("删除注册节点失败：" + e.getMessage());
        }
    }

    public List<Map<String, Integer>> getDslist() {
        return null;
    }


}
